<?php

namespace app\api\controller;

use app\api\logic\Alipay;
use app\api\logic\Wxpay;
use app\company\logic\JiPush;
use think\Db;
class Shop extends Base
{
    //首页
    public function index(){
        //轮播图
        $slide = M('shop_slide')->order('sort asc')->select();
        foreach ($slide as $key=>$value){
            $slide[$key]['img'] = getImageUrl(str_replace('\\','/',$value['img']));
        }
        //推荐
        $recommend = M('goods')->where(['status'=>1,'is_recommend'=>1])->order('sort asc')
            ->field('images,price,name,id,market_price')
            ->limit(0,6)
            ->select();
        foreach ($recommend as $key=>$value){
            $recommend[$key]['img'] = getImageUrl(str_replace('\\','/',explode(',',$value['images'])[0]));
            unset($recommend[$key]['images']);
        }
        //分类
        $cate = M('goods_cate')->where('status',1)->order('sort asc')->select();
        foreach ($cate as $key=>$value){
            if(!empty($value['img'])){
                $cate[$key]['img'] = getImageUrl(str_replace('\\','/',$value['img']));
            }
        }
        $data = [
            'slide'=>$slide,
            'recommend'=>$recommend,
            'cate'=>$cate,
        ];
        return return_json(0,'成功',$data);
    }
    //分类搜索
    public function cate_search(){
        $cate_id = I('cate_id',0);//分类id 0课程分类  其他对应商品分类id 默认0
        $keyword = I('keyword','');
        $sort_type = I('sort_type',1); //1最新 时间倒序  2销量倒序  3价格倒序 4价格正序 默认1
        $page = I('page',1);
//        if(empty($cate_id)){//课程列表
//            $where = [];
//            if($sort_type == 1){
//                $order = 'create_time desc';
//            }elseif ($sort_type == 2){
//                $order = 'sales desc';
//            }elseif ($sort_type == 3){
//                $order = 'price desc';
//            }elseif ($sort_type == 4){
//                $order = 'price asc';
//            }
//            $where['name'] = ['like',"%{$keyword}%"];
//            $where['status'] = 1;
//            $res = M('course')->where($where)
//                ->field('id,name,image,price')
//                ->order($order)
//                ->paginate(11, false, page_param());
//            $count = M('course a')
//                ->where($where)
//                ->count();
//            $list = $res->items();
//            foreach ($list as $key=>$value){
//                $list[$key]['img'] = getImageUrl(str_replace('\\','/',$value['image']));
//                unset($list[$key]['image']);
//                $list[$key]['type'] = 2;
//            }
//        }else{//产品列表
            $where = [];
            if($sort_type == 1){
                $order = 'create_time desc';
            }elseif ($sort_type == 2){
                $order = 'sales desc';
            }elseif ($sort_type == 3){
                $order = 'price desc';
            }elseif ($sort_type == 4){
                $order = 'price asc';
            }
            if(!empty($cate_id)){
                $where['goods_cate_id'] = $cate_id;
            }
            $where['name'] = ['like',"%{$keyword}%"];
            $where['status'] = 1;
            $res = M('goods')->where($where)
                ->field('id,name,images,price,market_price')
                ->order($order)
                ->paginate(11, false, page_param());
            $count = M('goods a')
                ->where($where)
                ->count();
            $list = $res->items();
            foreach ($list as $key=>$value){
                $list[$key]['img'] = getImageUrl(str_replace('\\','/',explode(',',$value['images'])[0]));
                unset($list[$key]['images']);
                $list[$key]['type'] = 1;
            }
//        }
        $count_page = ceil($count / 11);
        $data = [
            'list' => $list,
            'page' => (int)$page,
            'count_page' => $count_page,
            'count' => $count
        ];
        return return_json(0, '获取成功', $data);
    }
    //产品详情
    public function goods_info(){
        $id = I('id',0);
        if(empty($id)){
            return return_json(1,'id不能为空');
        }
        $info = M('goods')->where('id',$id)
            ->field('id,name,images,price,sales,inventory,content,market_price')
            ->find();
        $info['content'] = htmlspecialchars_decode($info['content']);
        $host = 'https://'.$_SERVER['HTTP_HOST'];
//        var_dump($host);die;
        $info['content']= str_replace('<img src="','<img width="100%" src="'.$host,$info['content']);
        if(!empty($info['images'])) {
            $info['images'] = explode(',', $info['images']);
            foreach ($info['images'] as $key => $value) {
                $info['images'][$key] = getImageUrl(str_replace('\\', '/', $value));
            }
        }
        //型号
        $model = M('goods_model')->where('goods_id',$id)
            ->field('id,model_name,img')
            ->select();
        foreach ($model as $key=>$value){
            $model[$key]['img'] = getImageUrl($value['img']);
        }
        $data = [
            'info'=>$info,
            'model'=>$model,
        ];
        return return_json(0,'成功',$data);
    }
    //课程详情
    public function course_info(){
        $id = I('id',0);
        if(empty($id)){
            return return_json(1,'id不能为空');
        }
        $info = M('course')->where('id',$id)
            ->field('id,name,image,price,sales,inventory,content')
            ->find();
        $info['content'] = htmlspecialchars_decode($info['content']);
        $info['image'] = getImageUrl($info['image']);
        //型号
        $model = M('course_model')->where('course_id',$id)
            ->field('id,model_name,img')
            ->select();
        foreach ($model as $key=>$value){
            $model[$key]['img'] = getImageUrl($value['img']);
        }
        $data = [
            'info'=>$info,
            'model'=>$model,
        ];
        return return_json(0,'成功',$data);
    }
    //产品或购物车确认订单
    public function goods_order(){
        $type = I('type',1); //1产品  2购物车
        $goods_id = I('goods_id',0);
        $model_id = I('model_id',0);
        $sum = I('sum',1);
        $ids = I('ids','');
        if($type == 1){
            if(empty($goods_id)){
                return return_json(1,'产品id不能为空');
            }
            if(empty($model_id)){
                return return_json(1,'型号id不能为空');
            }
            $goods = M('goods')->where('id',$goods_id)->find();
            $model_id = (int)$model_id;
            $model = M('goods_model')->where('id',$model_id)->find();
            $list[] = [
                'goods_id'=>$goods_id,
                'sum'=>$sum,
                'name'=>$goods['name'],
                'price'=>$goods['price'],
                'img'=>getImageUrl(str_replace('\\','/',explode(',',$goods['images'])[0])),
                'model_name'=>$model['model_name'],
                'inventory'=>$goods['inventory'],
            ];
        }elseif ($type == 2){
            if(empty($ids)){
                return return_json(1,'购物车id不能为空');
            }
            $ids = json_decode(htmlspecialchars_decode($ids),true);
            $list = M('com_user_cart a')
                ->join('goods b','b.id=a.goods_id','left')
                ->join('goods_model c','c.id=a.model_id','left')
                ->where('a.id','in',$ids)
                ->field('a.goods_id,a.sum,b.name,b.price,b.images,c.model_name,b.inventory')
                ->select();
            foreach ($list as $key=>$value){
                $list[$key]['img'] = getImageUrl(str_replace('\\','/',explode(',',$value['images'])[0]));
                unset($list[$key]['images']);
            }
        }
        $addr = M('com_user_address a')
            ->join('region b','b.id=a.province_id','left')
            ->join('region c','c.id=a.city_id','left')
            ->join('region d','d.id=a.county_id','left')
            ->where(['a.user_id'=>$this->user_id,'a.is_default'=>1])
            ->field('a.user_name,a.mobile,a.detail_addr,b.name province_name,c.name city_name
            ,d.name county_name')
            ->find();
        if(empty($addr)){
            $addr = [];
        }
        $data = [
            'list'=>$list,
            'addr'=>$addr,
        ];
        return return_json(0,'成功',$data);
    }
    //地址三级联动数据
    public function get_address_data(){
        $list = M('region')->where('pid',0)->field('id,pid,code,name,type')->select();
        $data = M('region')->field('id,pid,code,name,type')->select();
        foreach ($list as $key=>$value){
            $list[$key]['list'] = $this->get_tree_address($data,$value['id']);
        }
        return return_json(0,'成功',$list);
    }
    public function get_tree_address($data,$id){
        $data_array = [];
        foreach ($data as $key=>$value){
            if($value['pid'] == $id){
                $list = $this->get_tree_address($data,$value['id']);
                if(!empty($list)){
                    $value['list'] = $list;
                }
                $data_array[] = $value;
            }
        }
        return $data_array;
    }
    //用户地址列表
    public function user_address_list(){
        $uid = $this->user_id;
        $list = M('com_user_address a')
            ->join('region b','b.id=a.province_id','left')
            ->join('region c','c.id=a.city_id','left')
            ->join('region d','d.id=a.county_id','left')
            ->where('user_id',$uid)
            ->field('a.id,a.user_name,a.mobile,a.province_id,a.city_id,a.county_id,a.detail_addr,a.is_default
            ,b.name province_name,c.name city_name
            ,d.name county_name')
            ->select();
        return return_json(0,'成功',$list);
    }
    //修改默认地址
    public function update_address_default(){
        $id = I('id',0);
        if(empty($id)){
           return return_json(1,'id不能为空');
        }
        DB::startTrans();
        try{
            //更新用户所有的默认状态;
            M('com_user_address')->where('user_id',$this->user_id)->update(['is_default'=>0]);
            //更新指定默认状态
            M('com_user_address')->where('id',$id)->update(['is_default'=>1]);
            DB::commit();
            return return_json(0);
        }catch (\Exception $e){
            DB::rollback();
            return return_json(1,$e->getMessage());
        }

    }
    //新增收货地址
    public function add_address(){
        $uid = $this->user_id;
        $user_name = I('user_name','');//姓名
        $mobile = I('mobile','');//手机
        $province_id = I('province_id',0);//省id
        $city_id = I('city_id',0);//市id
        $county_id = I('county_id',0);//区id
        $detail_addr = I('detail_addr','');//详细地址
        if(empty($user_name)){
            return return_json(1,'姓名不能为空');
        }
        if(empty($mobile)){
            return return_json(1,'手机号不能为空');
        }
        if(empty($province_id)){
            return return_json(1,'省id不能为空');
        }
        if(empty($city_id)){
            return return_json(1,'市id不能为空');
        }
        if(empty($detail_addr)){
            return return_json(1,'详细地址不能为空');
        }
        $data = [
            'com_id'=>$this->com_id,
            'user_id'=>$uid,
            'user_name'=>$user_name,
            'mobile'=>$mobile,
            'province_id'=>$province_id,
            'city_id'=>$city_id,
            'county_id'=>$county_id,
            'detail_addr'=>$detail_addr,
            'is_default'=>0,
        ];
        $res = M('com_user_address')->insertGetId($data);
        if(empty($res)){
            return return_json(1,'添加失败');
        }
        return return_json(0,'成功');
    }
    //删除收货地址
    public function del_address(){
        $id = I('id',0);
        if(empty($id)){
            return return_json(1,'id不能为空');
        }
        $res = M('com_user_address')->where('id',$id)->delete();
        if(empty($res)){
            return return_json(1,'删除失败');
        }
        return return_json(0);

    }
    //编辑收货地址提交
    public function update_address_submit(){
        $id = I('id',0);
        $user_name = I('user_name','');//姓名
        $mobile = I('mobile','');//手机
        $province_id = I('province_id',0);//省id
        $city_id = I('city_id',0);//市id
        $county_id = I('county_id',0);//区id
        $detail_addr = I('detail_addr','');//详细地址
        if(empty($id)){
            return return_json(1,'id不能为空');
        }
        if(empty($user_name)){
            return return_json(1,'姓名不能为空');
        }
        if(empty($mobile)){
            return return_json(1,'手机号不能为空');
        }
        if(empty($province_id)){
            return return_json(1,'省id不能为空');
        }
        if(empty($city_id)){
            return return_json(1,'市id不能为空');
        }
        if(empty($detail_addr)){
            return return_json(1,'详细地址不能为空');
        }
        $data = [
            'user_name'=>$user_name,
            'mobile'=>$mobile,
            'province_id'=>$province_id,
            'city_id'=>$city_id,
            'county_id'=>$county_id,
            'detail_addr'=>$detail_addr,
        ];
        $res = M('com_user_address')->where('id',$id)->update($data);
        if(empty($res)){
            return return_json(1,'修改失败');
        }
        return return_json(0,'成功');
    }
    //产品添加购物车
    public function add_cart(){
        $uid = $this->user_id;
        $goods_id = I('goods_id',0);
        $model_id = I('model_id',0);
        $sum = I('sum',0);
        $where = [];
        $where['user_id'] = $uid;
        $where['goods_id'] = $goods_id;
        $where['model_id'] = $model_id;
        $res = M('com_user_cart')->where($where)->find();
        if(empty($res)){
            $data = [
                'user_id'=>$uid,
                'goods_id'=>$goods_id,
                'model_id'=>$model_id,
                'sum'=>$sum,
            ];
            $res_a = M('com_user_cart')->insertGetId($data);
        }else{
            $data = [
                'sum'=>Db::raw('sum+'.$sum)
                ];
            $res_a = M('com_user_cart')->where('id',$res['id'])->update($data);
        }
        if(empty($res_a)){
            return return_json(1,'添加失败');
        }
        return return_json(0);
    }
    //删除购物车商品
    public function del_cart(){
        $ids = I('ids',0);
        if(empty($ids)){
            return return_json(1,'购物车id不能为空');
        }
        $ids = json_decode(htmlspecialchars_decode($ids),true);
        M('com_user_cart')->where('id','in',$ids)->delete();
        return return_json(0);
    }
    //购物车列表
    public function cart_list(){
        $uid = $this->user_id;
        $list = M('com_user_cart a')
            ->join('goods b','b.id=a.goods_id','left')
            ->join('goods_model c','c.id=a.model_id','left')
            ->where('a.user_id',$uid)
            ->field('a.*,b.name,b.images,b.price,c.model_name,b.inventory')
            ->select();
        foreach ($list as $key=>$value){
            $list[$key]['img'] = getImageUrl(str_replace('\\','/',explode(',',$value['images'])[0]));
            unset($list[$key]['images']);
        }
        return return_json(0,'成功',$list);
    }
    //产品提交订单
    public function goods_order_submit(){
        $uid = $this->user_id;
        $address = I('address','');//地址
        $mobile = I('mobile','');//手机号
        $user_name = I('user_name','');//姓名
        $total_price = I('total_price','');//总价
        $desc = I('desc','');//说明
        $list = I('list','');//产品信息
        $type = I('type',1);//1普通商品 2购物车商品
        $ids = I('ids','');//购物车id json数组

        if(empty($address)){
            return return_json(1,'地址不能为空');
        }
        if(empty($mobile)){
            return return_json(1,'手机号不能为空');
        }
        if(empty($user_name)){
            return return_json(1,'用户姓名不能为空');
        }
        if(empty($total_price)){
            return return_json(1,'总价不能为空');
        }
        if(empty($list)){
            return return_json(1,'商品信息不能为空');
        }
        DB::startTrans();
        try{
            //新建订单表
            $data_order = [
                'order_number'=>$this->get_order_number(),
                'user_id'=>$uid,
                'mobile'=>$mobile,
                'total_price'=>$total_price,
                'address'=>$address,
                'desc'=>$desc,
                'user_name'=>$user_name,
                'create_time'=>time(),
            ];
            $order_id = M('goods_order')->insertGetId($data_order);
            $list = json_decode(htmlspecialchars_decode($list),true);
            //新建订单产品表
            foreach ($list as $key=>$value){
                $data_goods = [
                    'goods_order_id'=>$order_id,
                    'goods_id'=>$value['goods_id'],
                    'goods_model'=>$value['model_name'],
                    'goods_num'=>$value['sum'],
                ];
                M('goods_order_relation')->insert($data_goods);
            }
            //删除购物车商品
            if($type == 2){
                if(!empty($ids)){
                    $ids = json_decode(htmlspecialchars_decode($ids),true);
                }
                M('com_user_cart')->where('id','in',$ids)->delete();
            }
            DB::commit();
            $data = [
                'order_id'=>$order_id
            ];
            return return_json(0,'成功',$data);
        }catch (\Exception $e){
            DB::rollback();
            return return_json(1,$e->getMessage());
        }
    }
    //课程提交订单
    public function course_order_submit(){
        $uid = $this->user_id;
        $total_price = I('total_price','');//总价
        $people_sum = I('people_sum',1);//报名数量
        $linkman = I('linkman','');//联系人
        $link_mobile = I('link_mobile','');//联系电话
        $course_id = I('course_id',0);//课程id

        if(empty($people_sum)){
            return return_json(1,'报名数量不能为空');
        }
        if(empty($linkman)){
            return return_json(1,'联系人不能为空');
        }
        if(empty($link_mobile)){
            return return_json(1,'联系电话不能为空');
        }
        if(empty($total_price)){
            return return_json(1,'总价不能为空');
        }

        if(empty($course_id)){
            return return_json(1,'课程id不能为空');
        }
        DB::startTrans();
        try{
            //新建订单表
            $data_order = [
                'order_number'=>$this->get_order_number(),
                'user_id'=>$uid,
                'course_id'=>$course_id,
                'total_price'=>$total_price,
                'people_sum'=>$people_sum,
                'linkman'=>$linkman,
                'link_mobile'=>$link_mobile,
                'create_time'=>time(),
            ];
            $order_id = M('course_order')->insertGetId($data_order);
            DB::commit();
            $data = [
                'order_id'=>$order_id
            ];
            return return_json(0,'成功',$data);
        }catch (\Exception $e){
            DB::rollback();
            return return_json(1,$e->getMessage());
        }
    }
    //我的订单
    public function my_order(){
        $uid = $this->user_id;
        $type = I('type',1);//1课程订单 2商品订单
        $status = I('status',0);//商品订单状态  0全部 1待发货  2待收发货 3订单完成 默认0
        $page = I('page',1);
        if($type == 1){
            //课程订单
            $where = [];
            $where['a.is_del'] = 0;
            $where['a.user_id'] = $uid;
            $where['a.pay_status'] = 1;
            $res = M('course_order a')
                ->join('course b','b.id=a.course_id','left')
                ->where($where)
                ->field('a.id,a.people_sum,a.linkman,b.name,b.image,a.total_price')
                ->order('a.create_time desc')
                ->paginate(11, false, page_param());
            $count = M('course_order a')
                ->where($where)
                ->count();
            $list = $res->items();
            foreach ($list as $key=>$value){
                $list[$key]['img'] = getImageUrl($value['image']);
            }
        }else{
            //商品订单
            $where = [];
            $where['a.is_del'] = 0;
            $where['a.user_id'] = $uid;
            if(empty($status)){
                $where['a.status'] = ['in',[1,2,3]];
            }else{
                $where['a.status'] = $status;
            }
            $res = M('goods_order a')->where($where)
                ->field('a.id,a.total_price,a.status')
                ->order('a.create_time desc')
                ->paginate(11, false, page_param());
            $count = M('goods_order a')
                ->where($where)
                ->count();
            $list = $res->items();
            foreach ($list as $key=>$value){
                $goods_list = M('goods_order_relation a')
                    ->join('goods b','b.id=a.goods_id')
                    ->where('a.goods_order_id',$value['id'])
                    ->field('a.goods_id,a.goods_model model_name,a.goods_num sum,b.images,b.name,b.price')
                    ->select();
                $total_sum = M('goods_order_relation a')
                    ->where('a.goods_order_id',$value['id'])
                    ->sum('a.goods_num');
                foreach ($goods_list as $k1=>$v1){
                    $goods_list[$k1]['img'] = getImageUrl(str_replace('\\','/',explode(',',$v1['images'])[0]));
                    unset($goods_list[$k1]['images']);
                }
                $list[$key]['goods_list'] = $goods_list;
                $list[$key]['total_sum'] = $total_sum;
            }
        }
        $count_page = ceil($count / 11);
        $data = [
            'list' => $list,
            'page' => (int)$page,
            'count_page' => $count_page,
            'count' => $count
        ];
        return return_json(0, '获取成功', $data);
    }
    //课程订单详情
    public function course_order_info(){
        $id = I('id',0);
        if(empty($id)){
             return return_json(1,'id不能为空');
        }
        $order = M('course_order a')
            ->join('course b','b.id=a.course_id','left')
            ->where('a.id',$id)
            ->field('a.order_number,a.people_sum,a.linkman,a.link_mobile,a.create_time,a.total_price
            ,a.model_name,b.image,b.name')
            ->find();
        $order['image'] = getImageUrl(str_replace('\\','/',$order['image']));
        $order['create_time'] = date('Y-m-d',$order['create_time']);
        return return_json(0,'成功',$order);
    }
    //商品订单详情
    public function goods_order_info(){
        $id = I('id',0);
        if(empty($id)){
            return return_json(1,'id不能为空');
        }
        $order = M('goods_order a')
            ->where('a.id',$id)
            ->field('a.order_number,a.user_name,a.mobile,a.address,a.create_time,a.total_price
            ,a.desc,a.status')
            ->find();
        $order['create_time'] = date('Y-m-d',$order['create_time']);
        $goods = M('goods_order_relation a')
            ->join('goods b','b.id=a.goods_id','left')
            ->where('goods_order_id',$id)
            ->field('a.goods_id,a.goods_model model_name,a.goods_num sum,b.name,b.images,b.price')
            ->select();
        $total_sum = M('goods_order_relation a')
            ->where('goods_order_id',$id)
            ->sum('a.goods_num');
        $order['total_sum'] = $total_sum;
        foreach ($goods as $key=>$value){
            $goods[$key]['img'] = getImageUrl(str_replace('\\','/',explode(',',$value['images'])[0]));
            unset($goods[$key]['images']);
        }
        $data = [
            'order'=>$order,
            'goods'=>$goods,
        ];
        return return_json(0,'成功',$data);
    }
    //支付
    public function order_pay(){
        $pay_type = I('pay_type',1);//支付类型 1支付宝 2微信
        $order_id = I('order_id',1); //订单id
        $order_type = I('order_type',1); //订单类型 1商品订单 2课程订单
        if($order_type == 1){
            $goods_order_relation = M('goods_order_relation a')
                ->join('goods b','b.id=a.goods_id')
                ->where('a.goods_order_id',$order_id)
                ->column('b.name');
            $body = implode(',',$goods_order_relation);
            $order = M('goods_order')->where('id',$order_id)->find();
            $order_number = $order['order_number'].'_1';
            $total_price = $order['total_price'];
        }else{
            $order = M('course_order')->where('id',$order_id)->find();
            $order_number = $order['order_number'].'_2';
            $total_price = $order['total_price'];
            $body = M('course')->where('id',$order['course_id'])->value('name');
        }
        try {
            if ($pay_type == 1) {
                $res = Alipay::payment($body, $order_number, $total_price);
                $data = [
                    'sdk' => $res,
                    'order_number' => $order['order_number'],
                    'total_price' => $order['total_price'],
                    'order_type' => $order_type,
                ];
            } elseif ($pay_type == 2) {
                $res = Wxpay::payment($body, $order_number, $total_price);
                $data = [
                    'wxpay' => $res,
                    'order_number' => $order['order_number'],
                    'total_price' => $order['total_price'],
                    'order_type' => $order_type,
                ];
            }
            return return_json(0, '获取成功', $data);
        }catch (\Exception $e){
            return return_json(1,$e->getMessage());
        }
    }
    //商品订单用户确认收货
    public function order_confirm(){
        $id = I('id',0);
        if(empty($id)){
            return return_json(1,'订单id不能为空');
        }
        Db::startTrans();
        try{
            M('goods_order')->where('id',$id)->update(['status'=>3]);
            //加销量减库存
            $list_goods = M('goods_order_relation')->where('goods_order_id',$id)->select();
            foreach ($list_goods as $k=>$v){
                $data = [
                    'sales'=>Db::raw('sales+'.$v['goods_num']),
                    'inventory'=>Db::raw('inventory-'.$v['goods_num']),
                ];
                M('goods')->where('id',$v['goods_id'])->update($data);
            }
            Db::commit();
            return return_json(0);
        }catch (\Exception $e){
            Db::rollback();
            return return_json(1,$e->getMessage());
        }
    }
    //测试极光推送
    public function push(){
        $user_id = '1';
        $title = 'stonecs';
        $content = 'stonestone';
        JiPush::push($user_id,$title,$content);
    }
    //购物车修改商品数量
    public function update_cart(){
        $id = I('id',0);
        $sum = I('sum',1);
        if(empty($id)){
            return return_json(1,'id不能为空');
        }
        if(empty($sum)){
            return return_json(1,'商品数量不能为空');
        }
        M('com_user_cart')->where('id',$id)->update(['sum'=>$sum]);
        return return_json(0);
    }



}
